<template>
  <div class="home">
    <!-- 科技感导航栏 -->
    <nav class="main-nav">
      <div class="nav-container">
        <ul class="nav-menu">
          <li class="nav-item active">
            <router-link to="/" class="nav-link">
              <span class="nav-text">首页</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/circle" class="nav-link">
              <span class="nav-text">校园圈子</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/activity" class="nav-link">
              <span class="nav-text">活动中心</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/errand" class="nav-link">
              <span class="nav-text">超级跑腿</span>
            </router-link>
          </li>
        </ul>
        
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索校园服务..."
            size="small"
            @keyup.enter="handleSearch"
          ></el-input>
        </div>
        
        <!-- 用户头像下拉菜单 -->
        <div class="user-profile">
          <el-dropdown>
            <div class="avatar-wrapper">
              <img :src="currentUser?.avatar || '/default-avatar.png'" alt="用户头像" class="user-avatar" />
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item divided>
                  欢迎，{{ currentUser?.nickname || currentUser?.username || '用户' }}
                </el-dropdown-item>
                <el-dropdown-item @click="goToProfile">
                  <el-icon :size="16"></el-icon>
                  <span>个人资料</span>
                </el-dropdown-item>
                <el-dropdown-item @click="goToAddress">
                  <el-icon :size="16"></el-icon>
                  <span>收货地址</span>
                </el-dropdown-item>
                <el-dropdown-item divided @click="logout">
                  <el-icon :size="16"></el-icon>
                  <span>退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </nav>
    
    <div class="content-wrapper">

    <el-card class="search-card">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索帖子..."
        suffix-icon="Search"
        @keyup.enter="handleSearch"
      ></el-input>
    </el-card>

    <el-card class="posts-card">
      <template #header>
        <div class="card-header">
          <span>最新帖子</span>
        </div>
      </template>
      <el-empty v-if="posts.length === 0 && !loading">
        <template #description>
          暂无帖子数据
        </template>
      </el-empty>
      <el-skeleton v-else-if="loading" :row="5" :columns="1" />
      <el-card v-for="post in posts" :key="post.id" class="post-item" :body-style="{ padding: '0px' }">
        <div class="post-header">
          <img :src="post.author.avatar || '/default-avatar.png'" alt="用户头像" class="avatar" />
          <div class="user-info">
            <div class="username">{{ post.author.username }}</div>
            <div class="post-time">{{ formatDate(post.created_at) }}</div>
          </div>
        </div>
        <div class="post-content">
          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-text">{{ post.content }}</p>
        </div>
        <div class="post-footer">
          <span class="post-meta"><i class="el-icon-view"></i> {{ post.views }}</span>
          <span class="post-meta"><i class="el-icon-message"></i> {{ post.comments }}</span>
          <span class="post-meta"><i class="el-icon-heart"></i> {{ post.likes }}</span>
        </div>
      </el-card>

      <div class="pagination-container" v-if="!loading">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { circleApi } from '../api'
import { getUserInfo } from '../api/user'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, ElDropdown, ElDropdownMenu, ElDropdownItem, ElInput } from 'element-plus'
import { getToken, removeToken } from '../utils/auth'
import { useRouter } from 'vue-router'

// 搜索关键词
const searchKeyword = ref('')

// 帖子数据
const posts = ref([])

// 加载状态
const loading = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 路由实例
const router = useRouter()

// 当前用户信息
const currentUser = ref(null)

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取帖子列表
const getPosts = async () => {
  try {
    // 检查是否有token
    const token = getToken()
    if (!token) {
      ElMessageBox.alert('请先登录', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/login')
        }
      })
      return
    }

    loading.value = true
    const response = await circleApi.getPosts({
      page: currentPage.value,
      page_size: pageSize.value,
      keyword: searchKeyword.value
    })
    // 修复数据获取路径，根据后端返回的实际格式
    const rawPosts = response.data?.list || response.results || []
    
    // 重点：将后端返回的扁平化author_avatar转换为前端使用的嵌套结构post.author.avatar
    posts.value = rawPosts.map(post => ({
      ...post,
      // 构建或完善author对象，确保author.avatar可用
      author: {
        ...(post.author || {}),
        avatar: post.author_avatar || (post.author?.avatar || null)
      }
    }))
    
    total.value = response.data?.count || response.count || 0
  } catch (error) {
    console.error('获取帖子失败:', error)
    // 处理401错误
    if (error.response && error.response.status === 401) {
      ElMessageBox.alert('登录已过期，请重新登录', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/login')
        }
      })
    } else {
      ElMessage.error('获取帖子失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

// 搜索帖子
const handleSearch = () => {
  currentPage.value = 1
  getPosts()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getPosts()
}

// 当前页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  getPosts()
}

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    const response = await getUserInfo()
    currentUser.value = response.data
    
    // 处理头像URL
    if (currentUser.value.avatar && typeof currentUser.value.avatar === 'string') {
      // 确保头像URL是正确的格式
      if (!currentUser.value.avatar.startsWith('http')) {
        // 检查是否已经以/开头
        if (!currentUser.value.avatar.startsWith('/')) {
          currentUser.value.avatar = '/api/' + currentUser.value.avatar
        } else if (!currentUser.value.avatar.startsWith('/media/')) {
          currentUser.value.avatar = '/api' + currentUser.value.avatar
        }
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 组件挂载时获取帖子和用户信息
onMounted(() => {
  getPosts()
  fetchCurrentUser()
})

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    removeToken()
    router.push('/login')
    ElMessage.success('退出登录成功')
  }).catch(() => {
    // 取消退出
  })
}

// 跳转到个人资料页面
const goToProfile = () => {
  router.push('/profile')
}

// 跳转到地址管理页面
const goToAddress = () => {
  router.push('/address')
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  background-color: #f8f9fa;
}

/* 科技感导航栏样式 */
.main-nav {
  background: linear-gradient(135deg, #000c40 0%, #203a43 100%);
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 4px 20px rgba(0, 191, 255, 0.3);
  border-bottom: 1px solid rgba(0, 191, 255, 0.3);
}

.main-nav::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(0, 191, 255, 0.8), transparent);
}

.nav-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  height: 60px;
  position: relative;
}

/* 导航菜单 */
.nav-menu {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
  position: relative;
  z-index: 1;
}

.nav-item {
  margin: 0;
  position: relative;
}

.nav-link {
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  color: #b0c4de;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.nav-link::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(0, 191, 255, 0.1), transparent);
  transform: translateX(-100%);
  transition: transform 0.5s ease;
}

.nav-link:hover::before {
  transform: translateX(100%);
}

.nav-link:hover {
  color: #00bfff;
  background: rgba(0, 191, 255, 0.05);
}

.nav-link:hover .nav-icon {
  transform: scale(1.2);
  color: #00bfff;
}

.nav-item.active .nav-link {
  color: #00bfff;
  background: rgba(0, 191, 255, 0.1);
  box-shadow: inset 0 0 20px rgba(0, 191, 255, 0.2);
}

.nav-item.active .nav-link::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, transparent, #00bfff, transparent);
}

.nav-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-right: 8px;
  color: #87ceeb;
  transition: all 0.3s ease;
}

.nav-text {
  position: relative;
  z-index: 1;
}

/* 搜索框 */
.search-box {
  position: relative;
  margin-left: auto;
  margin-right: 20px;
  width: 200px;
}

.search-box :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(0, 191, 255, 0.3);
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 191, 255, 0.1);
  transition: all 0.3s ease;
}

.search-box :deep(.el-input__wrapper:hover) {
  border-color: rgba(0, 191, 255, 0.5);
  box-shadow: 0 0 0 2px rgba(0, 191, 255, 0.2);
}

.search-box :deep(.el-input__wrapper.is-focus) {
  border-color: #00bfff;
  box-shadow: 0 0 0 2px rgba(0, 191, 255, 0.3);
}

.search-box :deep(.el-input__inner) {
  color: #b0c4de;
  background: transparent;
  height: 36px;
}

.search-box :deep(.el-input__placeholder) {
  color: #87ceeb;
}

/* 用户头像下拉菜单 */
.user-profile {
  position: relative;
  z-index: 10;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.avatar-wrapper:hover {
  background: rgba(0, 191, 255, 0.2);
  box-shadow: 0 0 15px rgba(0, 191, 255, 0.5);
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 2px solid rgba(0, 191, 255, 0.5);
  object-fit: cover;
}

.notification-dot {
  position: absolute;
  top: 2px;
  right: 2px;
  width: 10px;
  height: 10px;
  background: #ff4757;
  border: 2px solid #000c40;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 71, 87, 0.7);
  }
  70% {
    transform: scale(1.2);
    box-shadow: 0 0 0 8px rgba(255, 71, 87, 0);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 71, 87, 0);
  }
}

/* 下拉菜单样式 */
:deep(.el-dropdown-menu) {
  background: rgba(17, 25, 40, 0.95);
  border: 1px solid rgba(0, 191, 255, 0.3);
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10px);
  color: #b0c4de;
  padding: 8px 0;
}

:deep(.el-dropdown-menu__item) {
  color: #b0c4de;
  background: transparent;
  transition: all 0.3s ease;
  font-size: 14px;
  padding: 10px 20px;
}

:deep(.el-dropdown-menu__item:hover) {
  background: rgba(0, 191, 255, 0.1);
  color: #00bfff;
}

:deep(.el-dropdown-menu__item.is-disabled:hover) {
  background: transparent;
  color: #4b5563;
}

:deep(.el-dropdown-menu__item.divided::before) {
  border-top: 1px solid rgba(0, 191, 255, 0.2);
}

/* 图标样式 */
:deep(.el-icon) {
  margin-right: 8px;
  font-size: 16px;
}

/* 星空背景效果 */
.main-nav::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, #fff, transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent),
    radial-gradient(1px 1px at 130px 80px, #fff, transparent),
    radial-gradient(3px 3px at 160px 120px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 200px;
  opacity: 0.1;
  pointer-events: none;
}

/* 主要内容区 */
.content-wrapper {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
  position: relative;
}

/* 科技感背景效果 */
.home {
  background: linear-gradient(135deg, #0a1128 0%, #121e40 100%);
  min-height: 100vh;
  background-image: 
    radial-gradient(2px 2px at 20px 30px, rgba(255, 255, 255, 0.1), transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255, 255, 255, 0.1), transparent),
    radial-gradient(1px 1px at 90px 40px, rgba(255, 255, 255, 0.1), transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255, 255, 255, 0.1), transparent),
    radial-gradient(3px 3px at 160px 120px, rgba(255, 255, 255, 0.1), transparent),
    linear-gradient(135deg, #0a1128 0%, #121e40 100%);
  background-repeat: repeat;
  background-size: 200px 200px, 200px 200px, 200px 200px, 200px 200px, 200px 200px, 100% 100%;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 30px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(0, 191, 255, 0.2);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 191, 255, 0.1);
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.search-card:hover {
  box-shadow: 0 6px 16px rgba(0, 191, 255, 0.2);
  transform: translateY(-2px);
  border-color: rgba(0, 191, 255, 0.4);
}

.search-card :deep(.el-input__wrapper) {
  border-radius: 25px;
  border: 2px solid rgba(0, 191, 255, 0.2);
  background: rgba(255, 255, 255, 0.05);
  transition: all 0.3s ease;
  padding: 0 20px;
  height: 50px;
}

.search-card :deep(.el-input__wrapper):hover {
  border-color: rgba(0, 191, 255, 0.4);
  box-shadow: 0 0 0 3px rgba(0, 191, 255, 0.1);
}

.search-card :deep(.el-input__wrapper).is-focus {
  border-color: #00bfff;
  box-shadow: 0 0 0 3px rgba(0, 191, 255, 0.2);
}

.search-card :deep(.el-input__inner) {
  color: #b0c4de;
  background: transparent;
}

.search-card :deep(.el-input__placeholder) {
  color: #87ceeb;
}

/* 帖子卡片 */
.posts-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(0, 191, 255, 0.2);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 191, 255, 0.1);
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 1px solid rgba(0, 191, 255, 0.2);
}

.card-header span {
  font-size: 20px;
  font-weight: 600;
  color: #00bfff;
  text-shadow: 0 0 10px rgba(0, 191, 255, 0.3);
}

/* 帖子项 */
.post-item {
  margin: 20px 25px;
  border: 1px solid rgba(0, 191, 255, 0.2);
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.02);
}

.post-item:hover {
  box-shadow: 0 6px 16px rgba(0, 191, 255, 0.2);
  transform: translateY(-2px);
  border-color: #00bfff;
  background: rgba(255, 255, 255, 0.05);
}

.post-header {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background: rgba(0, 191, 255, 0.05);
  border-bottom: 1px solid rgba(0, 191, 255, 0.1);
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 15px;
  border: 3px solid #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-info .username {
  font-weight: 600;
  color: #b0c4de;
  margin: 0 0 5px 0;
}

.post-time {
  font-size: 12px;
  color: #87ceeb;
}

.post-content {
  padding: 20px;
}

.post-title {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 600;
  color: #00bfff;
  line-height: 1.4;
}

.post-text {
  margin: 0;
  color: #b0c4de;
  line-height: 1.8;
  font-size: 15px;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  padding: 15px 20px;
  background: rgba(0, 191, 255, 0.05);
  border-top: 1px solid rgba(0, 191, 255, 0.1);
}

.post-meta {
  color: #87ceeb;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: color 0.3s ease;
}

.post-meta:hover {
  color: #00bfff;
}

.post-meta :deep(.el-icon) {
  margin-right: 5px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.pagination-container :deep(.el-pagination) {
  display: inline-flex;
  align-items: center;
}

.pagination-container :deep(.el-pagination__total) {
  color: #87ceeb;
}

.pagination-container :deep(.el-pagination__sizes .el-input .el-input__wrapper) {
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.05);
  border-color: rgba(0, 191, 255, 0.3);
}

.pagination-container :deep(.el-pagination__sizes .el-input .el-input__inner) {
  color: #b0c4de;
  background: transparent;
}

.pagination-container :deep(.el-pagination__item) {
  border-radius: 6px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.05);
  border-color: rgba(0, 191, 255, 0.3);
  color: #87ceeb;
}

.pagination-container :deep(.el-pagination__item:hover) {
  color: #00bfff;
  border-color: #00bfff;
  background: rgba(0, 191, 255, 0.1);
}

.pagination-container :deep(.el-pagination__item.is-active) {
  background-color: #00bfff;
  border-color: #00bfff;
  color: #0a1128;
}

.pagination-container :deep(.el-pagination__button) {
  color: #87ceeb;
  background: rgba(255, 255, 255, 0.05);
  border-color: rgba(0, 191, 255, 0.3);
  transition: all 0.3s ease;
}

.pagination-container :deep(.el-pagination__button:hover:not(:disabled)) {
  color: #00bfff;
  border-color: #00bfff;
  background: rgba(0, 191, 255, 0.1);
}

.pagination-container :deep(.el-pagination__button:disabled) {
  color: rgba(135, 206, 235, 0.5);
  border-color: rgba(0, 191, 255, 0.1);
  background: rgba(255, 255, 255, 0.02);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-container {
    padding: 0 15px;
  }
  
  .nav-menu {
    display: none;
  }
  
  .content-wrapper {
    margin: 15px auto;
    padding: 0 15px;
  }
  
  .post-item {
    margin: 15px;
  }
}
</style>